<template>
  <BasicDrawer v-bind="$attrs" @register="registerDrawer" :title="getTitle" width="650" @ok="handleSubmit" destroyOnClose>
    <BasicForm @register="registerForm" />
  </BasicDrawer>
</template>
<script lang="ts" setup>
import {computed, ref, unref, useAttrs} from 'vue';
import {BasicForm, useForm} from '/@/components/Form/index';
import {formSchema} from './payPassage.data';
import {BasicDrawer, useDrawerInner} from '/@/components/Drawer';
import {getPayPassage, saveOrUpdatePayPassage} from './payPassage.api';
import {ColEx} from '/@/components/Form/src/types';
// 声明Emits
const emit = defineEmits(['success', 'register']);
const attrs = useAttrs()
const isUpdate = ref(true);
const rowId = ref('');
const payPassageRecord = ref<any>({})
const mchAppRecord = ref<any>({})
// 自适应列配置
const adaptiveColProps: Partial<ColEx> = {
  xs: 22, // <576px
  sm: 22, // ≥576px
  md: 22, // ≥768px
  lg: 22, // ≥992px
  xl: 22, // ≥1200px
  xxl: 22, // ≥1600px
}

//表单配置
const [registerForm, { setProps, resetFields, setFieldsValue, validate }] = useForm({
  layout: 'vertical',
  labelWidth: '100%',
  schemas: formSchema,
  showActionButtonGroup: false,
  wrapperCol: adaptiveColProps
});

//表单赋值
const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
  await resetFields();
  payPassageRecord.value = data.record.payPassage
  mchAppRecord.value = data.record.mchApp
  console.log("payPassage: ", data.record.payPassage);

  let showFooter = data?.showFooter ?? true
  setDrawerProps({ confirmLoading: false, showFooter })
  isUpdate.value = !!data?.isUpdate;
  const respData = await getPayPassage({id: payPassageRecord.value.id})
  if (typeof payPassageRecord.value === 'object') {
    setFieldsValue({
        ...respData,
    })
  }
  // 隐藏底部时禁用整个表单
  setProps({ disabled: !showFooter })
});
//获取标题
const getTitle = computed(() => (!unref(isUpdate) ? '新增支付通道' : '编辑支付通道'));

//提交事件
async function handleSubmit() {
  try {
    console.log("start submit");
    
    let values = await validate();
    values.appId = mchAppRecord.value.id
    values.wayCode = payPassageRecord.value.wayCode
    values.ifCode = payPassageRecord.value.ifCode

    setDrawerProps({ confirmLoading: true });
    console.log("submit: ", values);
    //提交表单
    await saveOrUpdatePayPassage(values, unref(isUpdate));
    //关闭弹窗
    closeDrawer();
    //刷新列表
    emit('success', { isUpdate: unref(isUpdate), values: { ...values, id: rowId.value } });
  } finally {
    setDrawerProps({ confirmLoading: false });
  }
}
</script>
